package com.sky.orangehireserver.modules.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.orangehireserver.common.domain.Organization;
import com.sky.orangehireserver.common.service.OrganizationService;
import com.sky.orangehireserver.enums.ResponseCodeEnum;
import com.sky.orangehireserver.exception.BizException;
import com.sky.orangehireserver.modules.admin.dto.OrganizationCreateDTO;
import com.sky.orangehireserver.modules.admin.dto.OrganizationQueryDTO;
import com.sky.orangehireserver.modules.admin.dto.OrganizationUpdateDTO;
import com.sky.orangehireserver.modules.admin.service.AdminEnterpriseService;
import com.sky.orangehireserver.modules.admin.vo.OrganizationVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 超级管理员企业管理服务实现类
 *
 * @author sky
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminEnterpriseServiceImpl implements AdminEnterpriseService {

    private final OrganizationService organizationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrganizationVO createOrganization(OrganizationCreateDTO createDTO) {
        log.info("开始创建企业，企业名称：{}", createDTO.getName());

        // 检查企业名称是否已存在
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Organization::getName, createDTO.getName());
        if (organizationService.count(queryWrapper) > 0) {
            throw new BizException("ORGANIZATION_NAME_EXISTS", "企业名称已存在");
        }

        // 检查联系人邮箱是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Organization::getContactEmail, createDTO.getContactEmail());
        if (organizationService.count(queryWrapper) > 0) {
            throw new BizException("CONTACT_EMAIL_EXISTS", "联系人邮箱已存在");
        }

        // 创建企业实体
        Organization organization = Organization.builder().name(createDTO.getName()).shortName(createDTO.getShortName()).status("active") // 新创建的企业默认为激活状态
                .industry(createDTO.getIndustry()).size(createDTO.getSize()).logoUrl(createDTO.getLogoUrl()).website(createDTO.getWebsite()).address(createDTO.getAddress()).contactName(createDTO.getContactName()).contactEmail(createDTO.getContactEmail()).contactPhone(createDTO.getContactPhone()).description(createDTO.getDescription()).createdAt(LocalDateTime.now()).updatedAt(LocalDateTime.now()).build();

        // 保存企业
        boolean saved = organizationService.save(organization);
        if (!saved) {
            throw new BizException(ResponseCodeEnum.SYSTEM_ERROR.getErrorCode(), "创建企业失败");
        }

        log.info("企业创建成功，企业ID：{}", organization.getId());
        return convertToVO(organization);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrganizationVO updateOrganization(OrganizationUpdateDTO updateDTO) {
        log.info("开始更新企业信息，企业ID：{}", updateDTO.getId());

        // 检查企业是否存在
        Organization existingOrg = organizationService.getById(updateDTO.getId());
        if (existingOrg == null) {
            throw new BizException("ORGANIZATION_NOT_FOUND", "企业不存在");
        }

        // 如果更新企业名称，检查新名称是否已被其他企业使用
        if (StrUtil.isNotBlank(updateDTO.getName()) && !updateDTO.getName().equals(existingOrg.getName())) {
            LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Organization::getName, updateDTO.getName()).ne(Organization::getId, updateDTO.getId());
            if (organizationService.count(queryWrapper) > 0) {
                throw new BizException("ORGANIZATION_NAME_EXISTS", "企业名称已存在");
            }
        }

        // 如果更新联系人邮箱，检查新邮箱是否已被其他企业使用
        if (StrUtil.isNotBlank(updateDTO.getContactEmail()) && !updateDTO.getContactEmail().equals(existingOrg.getContactEmail())) {
            LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Organization::getContactEmail, updateDTO.getContactEmail()).ne(Organization::getId, updateDTO.getId());
            if (organizationService.count(queryWrapper) > 0) {
                throw new BizException("CONTACT_EMAIL_EXISTS", "联系人邮箱已存在");
            }
        }

        // 更新企业信息（只更新非空字段）
        Organization updateOrg = new Organization();
        updateOrg.setId(updateDTO.getId());
        updateOrg.setUpdatedAt(LocalDateTime.now());

        if (StrUtil.isNotBlank(updateDTO.getName())) {
            updateOrg.setName(updateDTO.getName());
        }
        if (StrUtil.isNotBlank(updateDTO.getShortName())) {
            updateOrg.setShortName(updateDTO.getShortName());
        }
        if (StrUtil.isNotBlank(updateDTO.getStatus())) {
            updateOrg.setStatus(updateDTO.getStatus());
        }
        if (StrUtil.isNotBlank(updateDTO.getIndustry())) {
            updateOrg.setIndustry(updateDTO.getIndustry());
        }
        if (StrUtil.isNotBlank(updateDTO.getSize())) {
            updateOrg.setSize(updateDTO.getSize());
        }
        if (StrUtil.isNotBlank(updateDTO.getLogoUrl())) {
            updateOrg.setLogoUrl(updateDTO.getLogoUrl());
        }
        if (StrUtil.isNotBlank(updateDTO.getWebsite())) {
            updateOrg.setWebsite(updateDTO.getWebsite());
        }
        if (StrUtil.isNotBlank(updateDTO.getAddress())) {
            updateOrg.setAddress(updateDTO.getAddress());
        }
        if (StrUtil.isNotBlank(updateDTO.getContactName())) {
            updateOrg.setContactName(updateDTO.getContactName());
        }
        if (StrUtil.isNotBlank(updateDTO.getContactEmail())) {
            updateOrg.setContactEmail(updateDTO.getContactEmail());
        }
        if (StrUtil.isNotBlank(updateDTO.getContactPhone())) {
            updateOrg.setContactPhone(updateDTO.getContactPhone());
        }
        if (StrUtil.isNotBlank(updateDTO.getDescription())) {
            updateOrg.setDescription(updateDTO.getDescription());
        }

        // 执行更新
        boolean updated = organizationService.updateById(updateOrg);
        if (!updated) {
            throw new BizException(ResponseCodeEnum.SYSTEM_ERROR.getErrorCode(), "更新企业信息失败");
        }

        // 返回更新后的企业信息
        Organization updatedOrg = organizationService.getById(updateDTO.getId());
        log.info("企业信息更新成功，企业ID：{}", updateDTO.getId());
        return convertToVO(updatedOrg);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrganization(Long id) {
        log.info("开始删除企业，企业ID：{}", id);

        // 检查企业是否存在
        Organization organization = organizationService.getById(id);
        if (organization == null) {
            throw new BizException("ORGANIZATION_NOT_FOUND", "企业不存在");
        }

        // TODO: 检查企业下是否还有用户、职位等数据，如果有则不允许删除
        // 这里可以根据业务需求添加相关检查逻辑

        // 执行删除
        boolean deleted = organizationService.removeById(id);
        if (!deleted) {
            throw new BizException(ResponseCodeEnum.SYSTEM_ERROR.getErrorCode(), "删除企业失败");
        }

        log.info("企业删除成功，企业ID：{}", id);
    }

    @Override
    public OrganizationVO getOrganizationById(Long id) {
        log.info("查询企业详情，企业ID：{}", id);

        Organization organization = organizationService.getById(id);
        if (organization == null) {
            throw new BizException("ORGANIZATION_NOT_FOUND", "企业不存在");
        }

        return convertToVO(organization);
    }

    @Override
    public IPage<OrganizationVO> getOrganizationPage(OrganizationQueryDTO queryDTO) {
        log.info("分页查询企业列表，查询条件：{}", queryDTO);

        // 构建查询条件
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(queryDTO.getName()), Organization::getName, queryDTO.getName()).eq(StrUtil.isNotBlank(queryDTO.getStatus()), Organization::getStatus, queryDTO.getStatus()).eq(StrUtil.isNotBlank(queryDTO.getIndustry()), Organization::getIndustry, queryDTO.getIndustry()).eq(StringUtils.isNotBlank(String.valueOf(queryDTO.getSize())), Organization::getSize, queryDTO.getSize()).orderByDesc(Organization::getCreatedAt);

        // 分页查询
        Page<Organization> page = new Page<>(queryDTO.getCurrent(), Long.parseLong(String.valueOf(queryDTO.getSize())));
        IPage<Organization> organizationPage = organizationService.page(page, queryWrapper);

        // 转换为VO
        IPage<OrganizationVO> voPage = new Page<>(organizationPage.getCurrent(), organizationPage.getSize(), organizationPage.getTotal());
        List<OrganizationVO> voList = organizationPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());
        voPage.setRecords(voList);

        return voPage;
    }

    @Override
    public List<OrganizationVO> getAllOrganizations() {
        log.info("查询所有企业列表");

        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Organization::getCreatedAt);

        List<Organization> organizations = organizationService.list(queryWrapper);
        return organizations.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enableOrganization(Long id) {
        log.info("启用企业，企业ID：{}", id);
        updateOrganizationStatus(id, "active");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disableOrganization(Long id) {
        log.info("禁用企业，企业ID：{}", id);
        updateOrganizationStatus(id, "inactive");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteOrganizations(List<Long> ids) {
        log.info("批量删除企业，企业ID列表：{}", ids);

        if (ids == null || ids.isEmpty()) {
            throw new BizException(ResponseCodeEnum.PARAM_NOT_VALID.getErrorCode(), "企业ID列表不能为空");
        }

        // TODO: 检查企业下是否还有用户、职位等数据，如果有则不允许删除
        // 这里可以根据业务需求添加相关检查逻辑

        // 执行批量删除
        boolean deleted = organizationService.removeByIds(ids);
        if (!deleted) {
            throw new BizException(ResponseCodeEnum.SYSTEM_ERROR.getErrorCode(), "批量删除企业失败");
        }

        log.info("批量删除企业成功，删除数量：{}", ids.size());
    }

    /**
     * 更新企业状态
     *
     * @param id 企业ID
     * @param status 状态
     */
    private void updateOrganizationStatus(Long id, String status) {
        // 检查企业是否存在
        Organization organization = organizationService.getById(id);
        if (organization == null) {
            throw new BizException("ORGANIZATION_NOT_FOUND", "企业不存在");
        }

        // 更新状态
        Organization updateOrg = new Organization();
        updateOrg.setId(id);
        updateOrg.setStatus(status);
        updateOrg.setUpdatedAt(LocalDateTime.now());

        boolean updated = organizationService.updateById(updateOrg);
        if (!updated) {
            throw new BizException(ResponseCodeEnum.SYSTEM_ERROR.getErrorCode(), "更新企业状态失败");
        }
    }

    /**
     * 将Organization实体转换为OrganizationVO
     *
     * @param organization 企业实体
     * @return 企业VO
     */
    private OrganizationVO convertToVO(Organization organization) {
        return BeanUtil.copyProperties(organization, OrganizationVO.class);
    }
}